import { Tabs, Typography, Button, message, Spin } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import React, { useState } from 'react'
import ReactMarkdown from 'react-markdown'
import { CopyOutlined } from '@ant-design/icons'
import {useEffect } from 'react'
import rehypeMathjax from 'rehype-mathjax/svg'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import { CodeBlock } from '@/modals/formModal/chatMessage/codeBlock'

const { Text } = Typography

interface ResultPanelProps {
  running: boolean
  results: any
}

interface Content {
  type: 'markdown' | 'json'
  content: string 
}

const ResultCont: React.FC<ResultPanelProps> = ({ running, results }) => {
  const [resultConent,setResultConent] = useState<Content>(null)

  useEffect(() => {
    if (!results) {
      return 
    }

    if (!results.var_map || Object.keys(results.var_map).length === 0) {
      const content = results?.output_msg;
      try {
        const jsonContent = JSON.parse(content);
        // 确保解析后的内容是对象或数组
        if (typeof jsonContent === 'object' && jsonContent !== null) {
          setResultConent({
            type: 'json',
            content: JSON.stringify(jsonContent, null, 2)
          });
          return;
        }
      } catch {}
      
      // 不是有效的JSON对象/数组，按markdown处理
      setResultConent({
        type: 'markdown',
        content: content?.replace(/\n/g, '  \n')
      });
      return;
    }
    const varMapKeys = Object.keys(results.var_map)
    if (varMapKeys.length === 1) {
      const content = results.var_map[varMapKeys[0]]
      // 判断内容类型
      if (content && typeof content === 'object') {
        setResultConent({
          type: 'json',
          content: JSON.stringify(content, null, 2)
        })
      } else {
        if(content){
          setResultConent({
            type: 'markdown',
            content: content?.replace(/\n/g, '  \n')
          })
        }else{
          setResultConent({
            type: 'markdown',
            content: results?.output_msg?.replace(/\n/g, '  \n')
          })
        }
      }
      return
    }
    
    setResultConent({
      type: 'json',
      content: JSON.stringify(results.var_map, null, 2)
    })
  }, [results])
  
  const handleCopy = (text: string) => {
    navigator.clipboard.writeText(text)
      .then(() => message.success('复制成功'))
      .catch(() => message.error('复制失败'))
  }
  
  return (
    <div className="h-full">
      {running ? (
        <div className="text-center py-4">
          <Spin 
            indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />} 
            className="mr-2"
          />
          正在运行中...
        </div>
      ) : (resultConent && (
        <div className="min-h-[200px] max-h-[calc(100vh-250px)] bg-gray-50 p-2 rounded-lg overflow-auto">
          <div className="flex justify-end">
            <Button 
              type="text" 
              icon={<CopyOutlined />}
              onClick={() => handleCopy(resultConent.content)}
            >
              复制
            </Button>
          </div>
          {resultConent.type === 'markdown' ? (
            console.log(resultConent.content),
            <div className="bg-white px-4 rounded-md text-[14px]">
              <ReactMarkdown
                remarkPlugins={[remarkGfm, remarkMath]}
                rehypePlugins={[rehypeMathjax]}
                className="markdown prose inline-block break-words dark:prose-invert"
                        components={{
                          code: ({ node, inline, className, children, ...props }) => {
                            if (children.length) {
                              if (children[0] === '▍') {
                                return <span className="form-modal-markdown-span">▍</span>
                              }

                              children[0] = (children[0] as string).replace('`▍`', '▍')
                            }

                            const match = /language-(\w+)/.exec(className || '')

                            return !inline ? (
                              <CodeBlock
                                key={Math.random()}
                                language={(match && match[1]) || ''}
                                value={String(children).replace(/\n$/, '')}
                                {...props}
                              />
                            ) : (
                              <code className={className} {...props}>
                                {children}
                              </code>
                            )
                          }
                        }}
                >
                  {resultConent.content}
              </ReactMarkdown>
            </div>
          ) : (
            <Text className="block h-full">
              <pre className="whitespace-pre-wrap break-all bg-white p-4 rounded-md text-[12px] h-full">
                {resultConent.content}
              </pre>
            </Text>
          )}
        </div>
      ))}
    </div>
  )
}

export default ResultCont